<template>
  <div class="tracking-drawer">
    <el-drawer :visible.sync="visible" :before-close="handleClose" title="运单轨迹详情" size="60%" direction="rtl">
      <div class="drawer-content" v-loading="loading">
        <!-- 运单基本信息 -->
        <div class="shipment-info" v-if="shipmentInfo">
          <el-card shadow="never" class="info-card">
            <div slot="header" class="card-header">
              <span>运单基本信息</span>
            </div>
            <div class="info-content">
              <div class="info-row">
                <div class="info-item">
                  <span class="label">运单号：</span>
                  <span class="value">{{ shipmentInfo.billNo }}</span>
                </div>
                <div class="info-item">
                  <span class="label">运单状态：</span>
                  <dict-tag :options="dict.type.bill_status" :value="shipmentInfo.billStatus" />
                </div>
                <div class="info-item">
                  <span class="label">目的地：</span>
                  <span class="value">{{ shipmentInfo.addressB }}</span>
                </div>
              </div>
              <div class="info-row">
                <div class="info-item">
                  <span class="label">收货联系人：</span>
                  <span class="value">{{ shipmentInfo.contactB }}</span>
                </div>
                <div class="info-item">
                  <span class="label">联系电话：</span>
                  <span class="value">{{ shipmentInfo.phoneB }}</span>
                </div>
                <div class="info-item">
                  <span class="label">创建时间：</span>
                  <span class="value">{{ parseTime(shipmentInfo.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 轨迹查看和展示模式切换 -->
        <div class="tracking-mode-switch">
          <el-card shadow="never" class="mode-card">
            <div class="mode-content">
              <div class="mode-section">
                <span class="mode-label">轨迹查看模式：</span>
                <el-radio-group v-model="viewMode" @change="handleViewModeChange">
                  <el-radio label="overall">总体轨迹</el-radio>
                  <el-radio label="daily">按天查看</el-radio>
                </el-radio-group>

                <!-- 按天查看时的日期选择 -->
                <div v-if="viewMode === 'daily'" class="date-selector">
                  <el-select v-model="selectedDate" placeholder="选择查看日期" @change="handleDateChange"
                    style="width: 150px; margin-left: 20px;">
                    <el-option v-for="date in availableDates" :key="date" :label="date" :value="date" />
                  </el-select>
                </div>
              </div>

              <div class="mode-section">
                <span class="mode-label">轨迹展示：</span>
                <el-radio-group v-model="displayMode" @change="handleDisplayModeChange">
                  <el-radio label="timeline">时间线</el-radio>
                  <el-radio label="map">地图轨迹</el-radio>
                </el-radio-group>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 地图轨迹展示 -->
        <div v-if="displayMode === 'map'" class="tracking-map">
          <el-card shadow="never" class="map-card">
            <div slot="header" class="card-header">
              <span>运单轨迹地图</span>
              <el-button type="text" icon="el-icon-refresh" @click="refreshTracking" size="small">
                刷新
              </el-button>
            </div>
            <div class="map-container">
              <!-- 使用高德地图组件 -->
              <MapContainer ref="mapContainer" :center="mapCenter" :zoom="mapZoom" :editable="false"
                :showFullscreen="true" height="400px" @map-loaded="onMapLoaded" />
              <div class="map-legend">
                <div class="legend-item">
                  <span class="legend-icon start"></span>
                  <span class="legend-text">起点</span>
                </div>
                <div class="legend-item">
                  <span class="legend-icon current"></span>
                  <span class="legend-text">当前位置</span>
                </div>
                <div class="legend-item">
                  <span class="legend-icon transit"></span>
                  <span class="legend-text">途经点</span>
                </div>
                <div class="legend-item">
                  <span class="legend-icon end"></span>
                  <span class="legend-text">终点</span>
                </div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 轨迹时间线 -->
        <div v-if="displayMode === 'timeline'" class="tracking-timeline">
          <el-card shadow="never" class="timeline-card">
            <div slot="header" class="card-header">
              <span>运单轨迹</span>
              <el-button type="text" icon="el-icon-refresh" @click="refreshTracking" size="small">
                刷新
              </el-button>
            </div>

            <!-- 总体轨迹显示 -->
            <div v-if="viewMode === 'overall'" class="overall-timeline">
              <el-timeline v-if="trackingList.length > 0">
                <el-timeline-item v-for="(item, index) in trackingList" :key="item.trackId"
                  :timestamp="parseTime(item.trackTime, '{y}-{m}-{d} {h}:{i}')"
                  :type="getTrackingType(item.trackType || item.trackStatus || '运输中')"
                  :icon="getTrackingIcon(item.trackType || item.trackStatus || '运输中')" placement="top">
                  <div class="timeline-content">
                    <div class="timeline-header">
                      <span class="status-text">【{{ item.deviationStatus }}{{ item.arrivalDeviation }}小时】</span>
                      <span class="location">{{ item.province }}{{ item.city }}{{ item.district }}</span>
                    </div>
                    <div class="timeline-body">
                      <p class="remark">{{ item.trackDesc }}</p>
                      <p class="address" v-if="item.address">
                        <i class="el-icon-location-outline"></i>
                        地址：{{ item.address }}
                      </p>
                      <p class="operator" v-if="item.operator">
                        <i class="el-icon-user"></i>
                        操作人：{{ item.operator }}
                      </p>
                    </div>
                  </div>
                </el-timeline-item>
              </el-timeline>
              <el-empty v-else description="暂无轨迹信息" />
            </div>

            <!-- 按天轨迹显示 -->
            <div v-if="viewMode === 'daily'" class="daily-timeline">
              <div v-if="dailyTracking.length > 0">
                <div v-for="dayData in dailyTracking" :key="dayData.date" class="daily-section">
                  <div class="daily-header">
                    <h4>{{ dayData.date }}</h4>
                    <el-tag size="mini" type="info">{{ (dayData.tracks && dayData.tracks.length) || 0 }}条记录</el-tag>
                  </div>
                  <el-timeline>
                    <el-timeline-item v-for="item in (dayData.tracks || [])" :key="item.trackId"
                      :timestamp="parseTime(item.trackTime, '{h}:{i}')"
                      :type="getTrackingType(item.trackType || item.trackStatus || '运输中')"
                      :icon="getTrackingIcon(item.trackType || item.trackStatus || '运输中')" placement="top">
                      <div class="timeline-content">
                        <div class="timeline-header">
                          <span class="status-text">【{{ item.deviationStatus }}{{ item.arrivalDeviation }}小时】</span>
                          <span class="location">{{ item.province }}{{ item.city }}{{ item.district }}</span>
                        </div>
                        <div class="timeline-body">
                          <p class="remark">{{ item.trackDesc }}</p>
                          <p class="address" v-if="item.address">
                            <i class="el-icon-location-outline"></i>
                            地址：{{ item.address }}
                          </p>
                          <p class="operator" v-if="item.operator">
                            <i class="el-icon-user"></i>
                            操作人：{{ item.operator }}
                          </p>
                        </div>
                      </div>
                    </el-timeline-item>
                  </el-timeline>
                </div>
              </div>
              <el-empty v-else description="暂无轨迹信息" />
            </div>
          </el-card>
        </div>

        <!-- 运输计划列表 -->
        <div class="transport-plan-section">
          <el-card shadow="never" class="plan-card">
            <div slot="header" class="card-header">
              <span>运输计划</span>
              <el-button type="text" icon="el-icon-refresh" @click="refreshTransportPlan" size="small">
                刷新
              </el-button>
            </div>
            <div v-if="transportPlans.length === 0 && !planLoading">
              <el-empty description="暂无运输计划" :image-size="60"></el-empty>
            </div>
            <el-table v-else :data="transportPlans" style="width: 100%" max-height="300" v-loading="planLoading"
              size="small">
              <el-table-column type="index" width="50" align="center" label="序号" />
              <el-table-column prop="nodeType" label="节点类型" width="80" align="center">
                <template slot-scope="scope">
                  <el-tag
                    :type="scope.row.nodeType === '起点' ? 'success' : scope.row.nodeType === '终点' ? 'danger' : 'info'"
                    size="mini">
                    {{ scope.row.nodeType }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="city" label="城市" width="200" />
              <el-table-column prop="estimatedDuration" label="计划到达时间" width="150" align="center">
                <template slot-scope="scope">
                  <span v-if="getEstimatedArrivalTime(scope.row)">{{ getEstimatedArrivalTime(scope.row) }}</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="arrivalTime" label="出发/到达时间" width="150" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.arrivalTime">{{ parseTime(scope.row.arrivalTime, '{y}-{m}-{d} {h}:{i}')
                    }}</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="arrivalDeviation" label="偏差时间" width="120" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.arrivalDeviation !== null && scope.row.arrivalDeviation !== undefined">{{
                    scope.row.arrivalDeviation }}</span>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="deviationStatus" label="偏差状态" width="100" align="center">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.deviation_status" :value="scope.row.deviationStatus" />
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="150" align="center">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { getLocationLogList } from '../api/comprehensive'
import { parseTime } from '@/utils/ruoyi'
import { listPlan } from '@/api/system/plan'
import MapContainer from '@/components/MapContainer/index.vue' // 引入高德地图组件

export default {
  name: 'TrackingDrawer',
  dicts: ['bill_status', 'deviation_status'],
  components: {
    MapContainer
  },
  props: {
    // 抽屉显示状态
    visible: {
      type: Boolean,
      default: false
    },
    // 运单信息
    shipmentInfo: {
      type: Object,
      default: null
    }
  },
  data () {
    return {
      // 加载状态
      loading: false,
      // 查看模式
      viewMode: 'overall',
      // 展示模式
      displayMode: 'timeline',
      // 轨迹列表
      trackingList: [],
      // 选中的日期
      selectedDate: '',
      // 可用日期列表
      availableDates: [],
      // 地图实例
      map: null,
      // 地图标记点
      markers: [],
      // 当前位置标记
      currentMarker: null,
      // 地图中心点
      mapCenter: [116.397428, 39.90923], // 默认中心点
      // 地图缩放级别
      mapZoom: 10,
      // 轨迹路线
      polyline: null,
      // 图标缓存
      iconCache: new Map(),
      // 运输计划相关
      transportPlans: [],
      planLoading: false,
      // 城市标签标记
      cityMarkers: []
    }
  },
  computed: {
    /** 按天分组的轨迹数据 */
    dailyTracking () {
      return this.getDailyTrackingData()
    }
  },
  watch: {
    visible (val) {
      if (val && this.shipmentInfo) {
        this.loadTrackingData()
        this.loadTransportPlan()
      }
    },
    shipmentInfo (val) {
      if (val && this.visible) {
        this.loadTrackingData()
        this.loadTransportPlan()
      }
    }
  },
  methods: {
    // 解析时间
    parseTime,

    /** 加载轨迹数据 */
    async loadTrackingData () {
      if (!this.shipmentInfo || !this.shipmentInfo.id) return

      this.loading = true
      try {
        // 使用新的API获取定位日志数据
        const response = await getLocationLogList(this.shipmentInfo.id)

        if (response && response.code === 200) {
          const locationLogs = response.rows || []

          // 将定位日志数据转换为轨迹数据格式
          this.trackingList = this.convertLocationLogsToTrackingList(locationLogs)

          // 提取可用日期
          this.extractAvailableDates()

          // 如果当前是地图模式且地图已加载，重新初始化地图
          if (this.displayMode === 'map' && this.map) {
            this.$nextTick(() => {
              this.initMap()
            })
          }
        } else {
          console.warn('定位日志数据为空或格式不正确:', response)
          this.trackingList = []
        }
      } catch (error) {
        console.error('加载定位日志数据失败:', error)
        this.$message.error('加载轨迹数据失败')
        this.trackingList = []
      } finally {
        this.loading = false
      }
    },

    /** 提取可用日期 */
    extractAvailableDates () {
      const dates = new Set()
      if (this.trackingList && Array.isArray(this.trackingList)) {
        this.trackingList.forEach(item => {
          if (item && item.trackTime) {
            const date = item.trackTime.split(' ')[0]
            dates.add(date)
          }
        })
      }
      this.availableDates = Array.from(dates).sort((a, b) => new Date(b) - new Date(a))
      if (this.availableDates.length > 0 && !this.selectedDate) {
        this.selectedDate = this.availableDates[0]
      }
    },

    /** 将定位日志数据转换为轨迹数据格式 */
    convertLocationLogsToTrackingList (locationLogs) {
      return locationLogs.map(log => ({
        trackId: log.id,
        trackTime: log.uploadTime,
        trackStatus: '运输中', // 可以根据需要设置状态
        trackType: '运输中',
        province: log.province,
        city: log.city,
        district: log.district,
        address: log.uploadAddress,
        longitude: log.longitude,
        latitude: log.latitude,
        operator: '系统', // 定位日志通常没有操作人
        trackDesc: `定位器${log.locatorCode}上传位置信息`,
        arrivalDeviation: log.arrivalDeviation, // 添加到达偏差字段
        deviationStatus: log.deviationStatus // 添加偏差状态字段
      })).sort((a, b) => new Date(a.trackTime) - new Date(b.trackTime)) // 按时间排序
    },

    /** 获取按天分组的轨迹数据 */
    getDailyTrackingData () {
      if (!this.trackingList || this.trackingList.length === 0) {
        return []
      }

      const dailyTracking = {}

      this.trackingList.forEach(item => {
        if (item && item.trackTime) {
          const date = item.trackTime.split(' ')[0]
          if (!dailyTracking[date]) {
            dailyTracking[date] = []
          }
          dailyTracking[date].push(item)
        }
      })

      // 转换为数组格式并按日期排序
      return Object.keys(dailyTracking)
        .sort((a, b) => new Date(b) - new Date(a))
        .map(date => ({
          date,
          tracks: dailyTracking[date]
        }))
    },

    /** 查看模式切换 */
    handleViewModeChange (mode) {
      this.viewMode = mode
      // 由于现在使用定位日志数据，不需要重新加载数据，只需要重新处理显示
      if (this.trackingList.length > 0) {
        this.extractAvailableDates()
      }
    },

    /** 日期选择变化 */
    handleDateChange (date) {
      this.selectedDate = date
      // 由于现在使用定位日志数据，不需要重新加载数据
      // 日期筛选可以在前端进行，或者根据实际需求调整
    },

    /** 刷新轨迹数据 */
    refreshTracking () {
      this.loadTrackingData()
    },

    /** 关闭抽屉 */
    handleClose () {
      this.$emit('close')
    },

    /** 获取轨迹类型 */
    getTrackingType (trackType) {
      const typeMap = {
        '发货': 'primary',    // 发货
        '运输中': 'warning',    // 运输中
        '派送中': 'info',       // 派送中
        '已签收': 'success',    // 已签收
        '异常': 'danger'      // 异常
      }
      return typeMap[trackType] || 'info'
    },

    /** 计算预计到达时间 */
    getEstimatedArrivalTime (row) {
      // 找到起点数据
      const startPoint = this.transportPlans.find(plan => plan.nodeType === '起点')

      if (!startPoint || !startPoint.arrivalTime || !row.estimatedDuration) {
        return null
      }

      try {
        // 解析起点到达时间
        const startTime = new Date(startPoint.arrivalTime)

        // 计算预计到达时间：起点时间 + 累计耗时（小时）
        const estimatedTime = new Date(startTime.getTime() + (row.estimatedDuration * 60 * 60 * 1000))

        // 格式化为 yyyy-MM-DD hh:mm 格式
        const year = estimatedTime.getFullYear()
        const month = String(estimatedTime.getMonth() + 1).padStart(2, '0')
        const day = String(estimatedTime.getDate()).padStart(2, '0')
        const hours = String(estimatedTime.getHours()).padStart(2, '0')
        const minutes = String(estimatedTime.getMinutes()).padStart(2, '0')

        return `${year}-${month}-${day} ${hours}:${minutes}`
      } catch (error) {
        console.error('计算预计到达时间失败:', error)
        return null
      }
    },

    /** 获取轨迹图标 */
    getTrackingIcon (trackType) {
      const iconMap = {
        '发货': 'el-icon-truck',      // 发货
        '运输中': 'el-icon-position',   // 运输中
        '派送中': 'el-icon-bicycle',    // 派送中
        '已签收': 'el-icon-check',      // 已签收
        '异常': 'el-icon-warning'     // 异常
      }
      return iconMap[trackType] || 'el-icon-info'
    },

    /** 获取地图标记图标 */
    getMapIcon (trackType, index, totalCount) {
      // 使用缓存
      if (this.iconCache.has(trackType)) {
        return this.iconCache.get(trackType)
      }

      // 确保 AMap 可用
      if (!window.AMap || !window.AMap.Icon || !window.AMap.Size) {
        console.warn('AMap.Icon 不可用，使用默认图标')
        return null
      }

      try {
        // 使用简单的颜色圆点图标，更可靠
        const colorMap = {
          '起点': '#67c23a',      // 绿色
          '终点': '#f56c6c',      // 红色
          '途经点': '#e6a23c',    // 橙色
          '发货': '#67c23a',      // 绿色
          '运输中': '#409eff',    // 蓝色
          '派送中': '#e6a23c',    // 橙色
          '已签收': '#f56c6c',    // 红色
          '异常': '#909399'       // 灰色
        }

        const color = colorMap[trackType] || colorMap['运输中']

        // 创建简单的圆点图标
        const canvas = document.createElement('canvas')
        canvas.width = 24
        canvas.height = 24
        const ctx = canvas.getContext('2d')

        // 绘制圆点
        ctx.fillStyle = color
        ctx.beginPath()
        ctx.arc(12, 12, 10, 0, 2 * Math.PI)
        ctx.fill()

        // 绘制白色边框
        ctx.strokeStyle = '#ffffff'
        ctx.lineWidth = 2
        ctx.stroke()

        // 在圆点中添加文字标识
        ctx.fillStyle = '#ffffff'
        ctx.font = 'bold 10px Arial'
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'

        let text = ''
        if (trackType === '起点') {
          text = '起'
        } else if (trackType === '终点') {
          text = '终'
        } else if (trackType === '途经点') {
          text = '途'
        } else {
          text = (index + 1).toString() // 显示序号
        }

        ctx.fillText(text, 12, 12)

        const icon = new window.AMap.Icon({
          size: new window.AMap.Size(24, 24),
          image: canvas.toDataURL(),
          imageSize: new window.AMap.Size(24, 24)
        })

        // 缓存图标
        this.iconCache.set(trackType, icon)
        return icon
      } catch (error) {
        console.error('创建自定义图标失败，使用默认样式:', error)
        // 返回 null，让标记使用默认样式
        return null
      }
    },

    /** 展示模式切换 */
    handleDisplayModeChange (mode) {
      this.displayMode = mode
      if (mode === 'map') {
        this.$nextTick(() => {
          if (this.map) {
            this.initMap()
          }
        })
      }
    },

    /** 检查 AMap API 是否完全可用 */
    isAMapReady () {
      return window.AMap &&
        window.AMap.Map &&
        window.AMap.Marker &&
        window.AMap.Polyline &&
        window.AMap.Icon &&
        window.AMap.Size &&
        window.AMap.Pixel &&
        window.AMap.InfoWindow &&
        window.AMap.Bounds
    },

    /** 地图加载完成回调 */
    onMapLoaded (map) {
      this.map = map
      console.log('地图加载完成')

      // 等待 AMap API 完全可用
      const checkAndInit = () => {
        if (this.isAMapReady()) {
          console.log('AMap API 完全可用，开始初始化')
          // 延迟初始化，确保地图完全加载
          this.$nextTick(() => {
            setTimeout(() => {
              // 如果有轨迹数据，立即绘制
              if (this.trackingList && this.trackingList.length > 0) {
                console.log('开始初始化地图，轨迹数据数量:', this.trackingList.length)
                this.initMap()
              }
            }, 200) // 增加延迟时间
          })
        } else {
          console.log('等待 AMap API 完全加载...')
          setTimeout(checkAndInit, 100)
        }
      }

      checkAndInit()
    },

    /** 初始化地图 */
    initMap () {
      if (!this.map || !this.isAMapReady()) {
        console.warn('地图或高德地图API未准备好，延迟重试')
        setTimeout(() => {
          this.initMap()
        }, 500)
        return
      }

      // 清除之前的地图
      this.clearMap()

      // 计算地图中心点和缩放级别
      this.calculateMapCenterAndZoom()

      // 绘制轨迹路线
      this.drawTrackingRoute()

      // 绘制轨迹点
      this.drawTrackingPoints()
    },

    /** 计算地图中心点和缩放级别 */
    calculateMapCenterAndZoom () {
      if (!this.map || !this.isAMapReady()) return
      if (!this.trackingList || this.trackingList.length === 0) return

      const validTrackings = this.trackingList.filter(item =>
        item.latitude && item.longitude &&
        !isNaN(parseFloat(item.latitude)) && !isNaN(parseFloat(item.longitude))
      )

      if (validTrackings.length === 0) return

      try {
        // 计算边界框
        const latitudes = validTrackings.map(item => parseFloat(item.latitude))
        const longitudes = validTrackings.map(item => parseFloat(item.longitude))

        const minLat = Math.min(...latitudes)
        const maxLat = Math.max(...latitudes)
        const minLng = Math.min(...longitudes)
        const maxLng = Math.max(...longitudes)

        // 验证计算结果
        if (isNaN(minLat) || isNaN(maxLat) || isNaN(minLng) || isNaN(maxLng)) {
          console.warn('计算地图边界时出现无效数值')
          return
        }

        // 计算中心点
        const centerLat = (minLat + maxLat) / 2
        const centerLng = (minLng + maxLng) / 2

        // 更新响应式数据，让 MapContainer 组件的 watch 来处理地图更新
        this.mapCenter = [centerLng, centerLat]

        // 根据轨迹点范围自动调整缩放级别
        if (validTrackings.length > 1) {
          // 计算合适的缩放级别
          const latDiff = maxLat - minLat
          const lngDiff = maxLng - minLng
          const maxDiff = Math.max(latDiff, lngDiff)

          if (maxDiff > 0.1) {
            this.mapZoom = 10
          } else if (maxDiff > 0.05) {
            this.mapZoom = 12
          } else if (maxDiff > 0.01) {
            this.mapZoom = 14
          } else {
            this.mapZoom = 16
          }
        } else {
          this.mapZoom = 15 // 单个点时使用固定缩放级别
        }

        console.log('更新地图中心点:', this.mapCenter, '缩放级别:', this.mapZoom)
      } catch (error) {
        console.error('计算地图中心点时出错:', error)
      }
    },

    /** 绘制轨迹路线 */
    drawTrackingRoute () {
      if (!this.map || !this.isAMapReady()) {
        console.warn('地图或高德地图API未准备好')
        return
      }

      if (!this.trackingList || !this.trackingList.length) return

      // 从 trackingList 提取经纬度坐标并转换为地图坐标
      let points = this.convertTrackingToPoints()

      if (points.length === 0) return

      try {
        // 绘制路线
        this.polyline = new window.AMap.Polyline({
          path: points,
          strokeColor: '#409eff',
          strokeWeight: 3,
          strokeStyle: 'solid',
          lineCap: 'round',
          lineJoin: 'round'
        })
        this.map.add(this.polyline)
      } catch (error) {
        console.error('创建轨迹路线时出错:', error)
      }
    },

    /** 绘制轨迹点 */
    drawTrackingPoints () {
      if (!this.map || !this.isAMapReady()) {
        console.warn('地图或高德地图API未准备好')
        return
      }

      if (!this.trackingList || !this.trackingList.length) return

      // 过滤出有效的经纬度数据
      const validTrackings = this.trackingList.filter(item =>
        item.latitude && item.longitude &&
        !isNaN(parseFloat(item.latitude)) && !isNaN(parseFloat(item.longitude))
      )

      if (validTrackings.length === 0) return

      try {
        // 清除之前的标记
        this.clearMarkers()

        // 创建轨迹点标记
        this.markers = validTrackings.map((item, index) => {
          const longitude = parseFloat(item.longitude)
          const latitude = parseFloat(item.latitude)

          // 再次验证经纬度有效性
          if (isNaN(longitude) || isNaN(latitude)) {
            console.warn('跳过无效坐标:', item)
            return null
          }

          // 确保 AMap.Pixel 可用
          if (!window.AMap || !window.AMap.Pixel) {
            console.warn('AMap.Pixel 不可用')
            return null
          }

          // 根据运输计划中的nodeType字段判断图标类型
          let iconType = this.getIconTypeByTransportPlan(item)

          const icon = this.getMapIcon(iconType, index, validTrackings.length)

          // 创建标记配置
          const markerConfig = {
            position: [longitude, latitude],
            extClass: 'tracking-marker'
          }

          if (icon) {
            // 使用自定义图标
            markerConfig.icon = icon
            markerConfig.offset = new window.AMap.Pixel(-12, -12) // 图标中心点（24x24图标的中心）
          } else {
            // 使用默认标记样式
            console.log(`使用默认标记样式: ${iconType}`)
          }

          const marker = new window.AMap.Marker(markerConfig)

          // 添加点击事件
          marker.on('click', () => {
            this.showTrackingDetail(item)
          })

          // 添加信息窗口
          const infoWindow = new window.AMap.InfoWindow({
            content: this.getTrackingInfoWindowContent(item),
            offset: new window.AMap.Pixel(0, -30) // 信息窗口偏移
          })
          marker.on('mouseover', () => {
            infoWindow.open(this.map, marker.getPosition())
          })
          marker.on('mouseout', () => {
            infoWindow.close()
          })

          return marker
        }).filter(marker => marker !== null) // 过滤掉空的标记

        // 添加轨迹点标记到地图
        this.markers.forEach(marker => this.map.add(marker))

        // 创建当前位置标记（如果还没到达终点）
        this.createCurrentMarker(validTrackings)

        // 添加运输计划城市标签
        this.addCityLabels()

      } catch (error) {
        console.error('创建地图标记时出错:', error)
      }
    },

    /** 创建当前位置标记 */
    createCurrentMarker (validTrackings) {
      if (!this.map || !this.isAMapReady() || !validTrackings.length) return

      try {
        // 检查是否已经到达终点
        const hasReachedEnd = this.hasReachedEndPoint(validTrackings)

        // 如果已经到达终点，则不显示当前位置
        if (hasReachedEnd) {
          // 清除之前的当前位置标记
          if (this.currentMarker) {
            this.map.remove(this.currentMarker)
            this.currentMarker = null
          }
          return
        }

        // 找到时间最近的点作为当前位置
        const currentPoint = validTrackings.reduce((latest, current) => {
          const latestTime = new Date(latest.trackTime || latest.createTime)
          const currentTime = new Date(current.trackTime || current.createTime)
          return currentTime > latestTime ? current : latest
        })

        if (!currentPoint) return

        const longitude = parseFloat(currentPoint.longitude)
        const latitude = parseFloat(currentPoint.latitude)

        if (isNaN(longitude) || isNaN(latitude)) return

        // 清除之前的当前位置标记
        if (this.currentMarker) {
          this.map.remove(this.currentMarker)
          this.currentMarker = null
        }

        // 判断当前位置是否为起点
        const isStartPoint = this.isPointMatchPlan(currentPoint, this.getStartPlan())

        // 创建当前位置图标
        const currentIcon = this.getCurrentPositionIcon(isStartPoint)

        // 创建当前位置标记
        this.currentMarker = new window.AMap.Marker({
          position: [longitude, latitude],
          icon: currentIcon,
          offset: new window.AMap.Pixel(-12, -12),
          extClass: 'current-position-marker'
        })

        // 添加到地图
        this.map.add(this.currentMarker)

        // 添加信息窗口
        const infoWindow = new window.AMap.InfoWindow({
          content: this.getCurrentPositionInfoWindowContent(currentPoint),
          offset: new window.AMap.Pixel(0, -30)
        })

        this.currentMarker.on('mouseover', () => {
          infoWindow.open(this.map, this.currentMarker.getPosition())
        })
        this.currentMarker.on('mouseout', () => {
          infoWindow.close()
        })

      } catch (error) {
        console.error('创建当前位置标记时出错:', error)
      }
    },

    /** 获取当前位置图标 */
    getCurrentPositionIcon (isStartPoint = false) {
      const cacheKey = isStartPoint ? 'current-start' : 'current'
      // 使用缓存
      if (this.iconCache.has(cacheKey)) {
        return this.iconCache.get(cacheKey)
      }

      try {
        // 创建圆点图标
        const canvas = document.createElement('canvas')
        canvas.width = 24
        canvas.height = 24
        const ctx = canvas.getContext('2d')

        // 根据是否为起点选择颜色
        const fillColor = isStartPoint ? '#67c23a' : '#409eff' // 起点绿色，当前位置蓝色

        // 绘制圆点
        ctx.fillStyle = fillColor
        ctx.beginPath()
        ctx.arc(12, 12, 10, 0, 2 * Math.PI)
        ctx.fill()

        // 绘制白色边框
        ctx.strokeStyle = '#ffffff'
        ctx.lineWidth = 2
        ctx.stroke()

        // 根据是否为起点绘制不同文字
        const text = isStartPoint ? '起' : '当'
        ctx.fillStyle = '#ffffff'
        ctx.font = 'bold 10px Arial'
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'
        ctx.fillText(text, 12, 12)

        const icon = new window.AMap.Icon({
          size: new window.AMap.Size(24, 24),
          image: canvas.toDataURL(),
          imageSize: new window.AMap.Size(24, 24)
        })

        // 缓存图标
        this.iconCache.set(cacheKey, icon)
        return icon
      } catch (error) {
        console.error('创建当前位置图标失败:', error)
        return null
      }
    },

    /** 获取当前位置信息窗口内容 */
    getCurrentPositionInfoWindowContent (item) {
      return `
        <div class="current-position-info-window">
          <h4>📍 当前位置</h4>
          <p><strong>时间：</strong>${this.parseTime(item.trackTime || item.createTime, '{y}-{m}-{d} {h}:{i}')}</p>
          <p><strong>地址：</strong>${item.address || '暂无地址'}</p>
          <p><strong>状态：</strong>${item.trackStatus || '运输中'}</p>
        </div>
      `
    },

    /** 添加运输计划城市标签 */
    addCityLabels () {
      if (!this.map || !this.isAMapReady() || !this.transportPlans.length) return

      try {
        // 清除之前的城市标签
        this.clearCityMarkers()

        // 为运输计划中的城市添加标签
        const cityMap = new Map() // 用于去重，一个城市只添加一个标签

        this.transportPlans.forEach(plan => {
          if (plan.city && !cityMap.has(plan.city)) {
            cityMap.set(plan.city, plan)

            // 根据节点类型确定标签样式
            const labelStyle = this.getCityLabelStyle(plan.nodeType)

            // 创建城市标签
            const label = new window.AMap.Text({
              text: plan.city,
              position: [plan.longitude || 0, plan.latitude || 0],
              style: labelStyle,
              offset: new window.AMap.Pixel(-50, -15)
            })

            this.cityMarkers.push(label)
            this.map.add(label)
          }
        })

      } catch (error) {
        console.error('添加城市标签时出错:', error)
      }
    },

    /** 获取城市标签样式 */
    getCityLabelStyle (nodeType) {
      const baseStyle = {
        fontSize: '12px',
        fontWeight: 'bold',
        padding: '4px 8px',
        borderRadius: '4px',
        border: '2px solid #fff',
        boxShadow: '0 2px 4px rgba(0,0,0,0.2)'
      }

      switch (nodeType) {
        case '起点':
          return {
            ...baseStyle,
            backgroundColor: '#67c23a',
            color: '#fff'
          }
        case '终点':
          return {
            ...baseStyle,
            backgroundColor: '#f56c6c',
            color: '#fff'
          }
        case '途经点':
          return {
            ...baseStyle,
            backgroundColor: '#e6a23c',
            color: '#fff'
          }
        default:
          return {
            ...baseStyle,
            backgroundColor: '#409eff',
            color: '#fff'
          }
      }
    },

    /** 清除标记 */
    clearMarkers () {
      if (this.markers && this.markers.length > 0) {
        this.markers.forEach(marker => {
          if (marker) {
            this.map.remove(marker)
          }
        })
      }
      this.markers = []
    },

    /** 根据运输计划中的nodeType字段判断图标类型 */
    getIconTypeByTransportPlan (trackingItem) {
      if (!this.transportPlans || this.transportPlans.length === 0) {
        return '途经点'
      }

      // 遍历运输计划，找到匹配的点位
      for (const plan of this.transportPlans) {
        if (this.isPointMatchPlan(trackingItem, plan)) {
          return plan.nodeType || '途经点'
        }
      }

      return '途经点'
    },

    /** 判断轨迹点是否匹配运输计划中的点位 */
    isPointMatchPlan (trackingItem, plan) {
      if (!plan || !plan.nodeType) {
        return false
      }

      // 比较城市名称
      const trackingCity = trackingItem.city || trackingItem.province || ''
      const planCity = plan.city || ''

      if (trackingCity && planCity && trackingCity.includes(planCity)) {
        return true
      }

      // 如果有经纬度信息，也可以比较坐标（允许一定误差）
      if (trackingItem.longitude && trackingItem.latitude &&
        plan.longitude && plan.latitude) {
        const trackingLng = parseFloat(trackingItem.longitude)
        const trackingLat = parseFloat(trackingItem.latitude)
        const planLng = parseFloat(plan.longitude)
        const planLat = parseFloat(plan.latitude)

        // 计算距离（简单计算，允许5公里误差）
        const distance = this.calculateDistance(trackingLat, trackingLng, planLat, planLng)
        if (distance <= 5) { // 5公里内认为是同一位置
          return true
        }
      }

      return false
    },

    /** 获取运输计划中的起点 */
    getStartPlan () {
      if (!this.transportPlans || this.transportPlans.length === 0) {
        return null
      }
      return this.transportPlans.find(plan => plan.nodeType === '起点')
    },

    /** 检查是否已经到达终点 */
    hasReachedEndPoint (validTrackings) {
      if (!this.transportPlans || this.transportPlans.length === 0) {
        return false
      }

      // 获取运输计划中的终点
      const endPlan = this.transportPlans.find(plan => plan.nodeType === '终点')
      if (!endPlan) {
        return false
      }

      // 检查轨迹点中是否有任何一个点匹配终点
      for (const tracking of validTrackings) {
        if (this.isPointMatchPlan(tracking, endPlan)) {
          return true
        }
      }

      return false
    },



    /** 计算两点间距离（公里） */
    calculateDistance (lat1, lng1, lat2, lng2) {
      const R = 6371 // 地球半径（公里）
      const dLat = this.deg2rad(lat2 - lat1)
      const dLng = this.deg2rad(lng2 - lng1)
      const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) *
        Math.sin(dLng / 2) * Math.sin(dLng / 2)
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
      return R * c
    },

    /** 角度转弧度 */
    deg2rad (deg) {
      return deg * (Math.PI / 180)
    },

    /** 清除城市标签 */
    clearCityMarkers () {
      if (this.cityMarkers && this.cityMarkers.length > 0) {
        this.cityMarkers.forEach(marker => {
          if (marker) {
            this.map.remove(marker)
          }
        })
      }
      this.cityMarkers = []
    },

    /** 将轨迹数据转换为地图坐标点 */
    convertTrackingToPoints () {
      if (!this.trackingList || !this.trackingList.length) return []

      // 过滤出有效的经纬度数据
      const validTrackings = this.trackingList.filter(item =>
        item.latitude && item.longitude &&
        !isNaN(parseFloat(item.latitude)) && !isNaN(parseFloat(item.longitude))
      )

      if (validTrackings.length === 0) return []

      // 直接返回经纬度坐标数组
      return validTrackings.map(item => [parseFloat(item.longitude), parseFloat(item.latitude)])
    },

    /** 获取轨迹信息窗口内容 */
    getTrackingInfoWindowContent (item) {
      return `
        <div class="tracking-info-window">
          <h4>【到达】 ${this.parseTime(item.trackTime, '{m}-{d} {h}:{i}')}</h4>

          <p><strong>地址：</strong>${item.address || '暂无地址'}</p>
          <p><strong>操作人：</strong>${item.operator || '暂无操作人'}</p>
        </div>
      `
    },

    /** 显示轨迹详情 */
    showTrackingDetail (item) {
      this.$emit('show-detail', item)
    },

    /** 清除地图 */
    clearMap () {
      if (!this.map) return

      try {
        // 清除轨迹路线
        if (this.polyline) {
          this.map.remove(this.polyline)
          this.polyline = null
        }

        // 清除轨迹标记
        this.clearMarkers()

        // 清除当前位置标记
        if (this.currentMarker) {
          this.map.remove(this.currentMarker)
          this.currentMarker = null
        }

        // 清除城市标签
        this.clearCityMarkers()

        // 清除图标缓存
        this.iconCache.clear()
      } catch (error) {
        console.error('清除地图元素时出错:', error)
        // 强制重置
        this.polyline = null
        this.markers = []
        this.currentMarker = null
        this.cityMarkers = []
        this.iconCache.clear()
      }
    },

    /** 加载运输计划 */
    async loadTransportPlan () {
      console.log('开始加载运输计划，运单信息:', this.shipmentInfo)

      if (!this.shipmentInfo.billNo) {
        console.log('运单编号为空，无法查询运输计划')
        return
      }

      this.planLoading = true
      try {
        console.log('查询运输计划，运单编号:', this.shipmentInfo.billNo)

        const response = await listPlan({
          billNo: this.shipmentInfo.billNo
        })

        console.log('运输计划查询响应:', response)

        if (response.code === 200) {
          this.transportPlans = response.rows || []
          console.log('运输计划查询成功，数量:', this.transportPlans.length)

          // 如果当前是地图模式且地图已加载，重新绘制地图以添加城市标签
          if (this.displayMode === 'map' && this.map) {
            this.$nextTick(() => {
              this.drawTrackingPoints()
            })
          }
        } else {
          console.error('查询运输计划失败:', response.msg)
        }
      } catch (error) {
        console.error('查询运输计划异常:', error)
      } finally {
        this.planLoading = false
      }
    },

    /** 刷新运输计划 */
    refreshTransportPlan () {
      this.loadTransportPlan()
    }
  }
}
</script>

<style lang="scss" scoped>
.tracking-drawer {
  ::v-deep .el-drawer {
    .el-drawer__header {
      padding: 20px 20px 10px;
      margin-bottom: 0;
      border-bottom: 1px solid #ebeef5;

      span {
        font-size: 18px;
        font-weight: 500;
        color: #303133;
      }
    }

    .el-drawer__body {
      padding: 0;
    }
  }
}

.drawer-content {
  height: 100%;
  overflow-y: auto;
  padding: 20px;

  .shipment-info {
    margin-bottom: 20px;

    .info-card {
      .card-header {
        font-weight: 500;
        color: #303133;
      }

      .info-content {
        .info-row {
          display: flex;
          margin-bottom: 15px;

          &:last-child {
            margin-bottom: 0;
          }

          .info-item {
            flex: 1;
            display: flex;
            align-items: center;

            .label {
              color: #606266;
              margin-right: 8px;
              white-space: nowrap;
            }

            .value {
              color: #303133;
              font-weight: 500;
            }
          }
        }
      }
    }
  }

  .tracking-mode-switch {
    margin-bottom: 20px;

    .mode-card {
      .mode-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;
        gap: 20px;

        .mode-section {
          display: flex;
          align-items: center;

          .mode-label {
            color: #606266;
            margin-right: 15px;
            white-space: nowrap;
          }

          .date-selector {
            display: flex;
            align-items: center;
          }
        }
      }
    }
  }

  .tracking-map {
    margin-bottom: 20px;

    .map-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: 500;
        color: #303133;
      }

      .map-container {
        position: relative;

        .map-view {
          width: 100%;
          height: 400px;
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          background: #f0f2f5;
        }

        // 确保地图组件的样式
        ::v-deep .map-container {
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          overflow: hidden;
        }

        .map-legend {
          position: absolute;
          top: 40px;
          right: 10px;
          background: rgba(255, 255, 255, 0.9);
          padding: 10px;
          border-radius: 4px;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
          z-index: 999;

          .legend-item {
            display: flex;
            align-items: center;
            margin-bottom: 5px;

            &:last-child {
              margin-bottom: 0;
            }

            .legend-icon {
              width: 12px;
              height: 12px;
              border-radius: 50%;
              margin-right: 8px;

              &.start {
                background: #67c23a;
              }

              &.current {
                background: #409eff;
              }

              &.transit {
                background: #e6a23c;
              }

              &.end {
                background: #f56c6c;
              }
            }

            .legend-text {
              font-size: 12px;
              color: #303133;
            }
          }
        }
      }
    }
  }

  .tracking-timeline {
    .timeline-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-weight: 500;
        color: #303133;
      }

      .overall-timeline,
      .daily-timeline {
        .timeline-content {
          .timeline-header {
            margin-bottom: 8px;

            .status-text {
              font-weight: 500;
              color: #409eff;
              margin-right: 10px;
            }

            .location {
              color: #303133;
              font-weight: 500;
            }
          }

          .timeline-body {
            .remark {
              color: #606266;
              margin: 5px 0;
              line-height: 1.5;
            }

            .address {
              color: #909399;
              font-size: 12px;
              margin: 5px 0 0;

              i {
                margin-right: 4px;
              }
            }

            .operator {
              color: #909399;
              font-size: 12px;
              margin: 5px 0 0;

              i {
                margin-right: 4px;
              }
            }
          }
        }
      }

      .daily-timeline {
        .daily-section {
          margin-bottom: 30px;

          &:last-child {
            margin-bottom: 0;
          }

          .daily-header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #ebeef5;

            h4 {
              margin: 0;
              color: #303133;
              font-size: 16px;
              margin-right: 10px;
            }
          }
        }
      }
    }
  }
}

::v-deep .el-timeline {
  .el-timeline-item__timestamp {
    color: #909399;
    font-size: 12px;
  }

  .el-timeline-item__wrapper {
    padding-left: 35px;
  }

  .el-timeline-item__tail {
    border-left: 2px solid #e4e7ed;
  }

  .el-timeline-item__node {
    width: 14px;
    height: 14px;
  }
}

::v-deep .tracking-info-window {
  padding: 10px;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border: 1px solid #ebeef5;

  h4 {
    margin-top: 0;
    margin-bottom: 5px;
    color: #303133;
    font-size: 16px;
  }

  p {
    margin: 5px 0;
    color: #606266;
    font-size: 14px;
    line-height: 1.6;

    strong {
      color: #303133;
    }
  }
}

.transport-plan-section {
  margin-top: 20px;

  .plan-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 500;
      color: #303133;
    }
  }
}
</style>
